<script setup>
import { ref, computed } from 'vue';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
import { Edit, SwitchButton, User } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus';
import { useUserStore } from '/src/store/user.js';

const store = useStore();
const router = useRouter();
const route = useRoute();

// 控制下拉菜单显示
const showDropdown = ref(false);
// 控制修改密码对话框
const showDialog = ref(false);

// 表单数据
const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 表单验证规则
const rules = ref({
  oldPassword: [
    {required: true, message: '请输入旧密码', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {
      min: 8,
      max: 16,
      message: '密码长度8-16位',
      trigger: ['blur', 'change']
    },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,16}$/,
      message: '需包含大小写字母和数字',
      trigger: ['blur', 'change']
    }
  ],
  confirmPassword: [
    {required: true, message: '请确认新密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ]
});

// 计算属性
const isLoggedIn = computed(() => store.getters.isLoggedIn);
const userName = computed(() => store.getters.userInfo?.username || '');
const userRole = computed(() => store.getters.userRole);

// 路由跳转方法
const goToRoute = (path) => {
  const userStore = useUserStore();
  router.push(path);
};

// 导航高亮判断
const isActiveRoute = (routePath) => {
  return route.path === routePath;
};

// 打开修改密码对话框
const openPasswordDialog = () => {
  showDialog.value = true;
  showDropdown.value = false;
};

// 提交修改密码
const submitPassword = async () => {
  try {
    store.dispatch('changePassword', {
      oldPassword: form.value.oldPassword,
      newPassword: form.value.newPassword
    });
    ElMessage.success('密码修改成功，请重新登录');
    store.dispatch('logout'); // 清除本地token
    router.push('/login'); // 跳转到登录页
    showDialog.value = false;
    form.value = {oldPassword: '', newPassword: '', confirmPassword: ''};
  } catch (error) {
    ElMessage.error(error.message || '密码修改失败');
  }
};

// 其他功能方法
const logout = () => {
  store.dispatch('logout');
  router.push('/login');
};

const goSmartLocker = () => goToRoute('/smart/locker');
const goException = () => goToRoute('/exception');
const goScan = () => goToRoute('/scan');
</script>

<template>
  <header class="header">
    <div class="logo">
      <span @click="goToRoute('/')" class="logo-text">快递柜系统</span>
    </div>

    <nav class="nav">
      <span @click="goToRoute('/home')" :class="['nav-item', { active: isActiveRoute('/home') }]">首页</span>
      <span @click="goToRoute('/order')" :class="['nav-item', { active: isActiveRoute('/order') }]">我的订单</span>
      <span @click="goToRoute('/address')" :class="['nav-item', { active: isActiveRoute('/address') }]">地址管理</span>

      <template v-if="userRole === 'courier'">
        <span @click="goScan" :class="['nav-item', { active: isActiveRoute('/scan') }]">扫码录入</span>
        <span @click="goToRoute('/order/update')" :class="['nav-item', { active: isActiveRoute('/order/update') }]">更新订单状态</span>
      </template>

      <template v-if="userRole === 'user'">
        <span @click="goSmartLocker"
              :class="['nav-item', { active: isActiveRoute('/smart/locker') }]">智能推荐快递柜</span>
      </template>
      <span @click="goToRoute('/profile')" :class="['nav-item', { active: isActiveRoute('/profile') }]">个人中心</span>
    </nav>

    <div class="user-info">
      <template v-if="isLoggedIn">
        <div class="user-avatar"
             @mouseenter="showDropdown = true"
             @mouseleave="showDropdown = false">
          <div style="display: flex; align-items: center; gap: 8px">
            <div class="avatar-wrapper">
              <el-icon :size="28" color="#fff">
                <User/>
              </el-icon>
            </div>
            <div class="username" style="font-size: 16px; color: white">
              {{userName}}
            </div>
          </div>
          <transition name="el-zoom-in-top">
            <div v-show="showDropdown" class="dropdown-menu">
              <div class="menu-item" @click="openPasswordDialog">
                <el-icon>
                  <Edit/>
                </el-icon>
                <span style="color: #e8772b; margin-left: 10px">修改密码</span>
              </div>
              <div class="menu-item" @click="logout">
                <el-icon>
                  <SwitchButton/>
                </el-icon>
                <span style="color: #cd1d1d; margin-left: 10px">退出登录</span>
              </div>
              <div class="menu-item" @click="goException">
                <span>异常处理</span>
              </div>
            </div>
          </transition>
        </div>
      </template>
      <template v-else>
        <el-button type="primary" @click="goToRoute('/login')">登录</el-button>
        <el-button type="danger" @click="goToRoute('/register')">注册</el-button>
      </template>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog
        v-model="showDialog"
        title="修改密码"
        width="500px"
        :close-on-click-modal="false">
      <el-form
          :model="form"
          :rules="rules"
          label-width="100px"
          status-icon>
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
              v-model="form.oldPassword"
              type="password"
              show-password
              placeholder="请输入当前密码"/>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="form.newPassword"
              type="password"
              show-password
              placeholder="8-16位，需包含大小写字母和数字"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="form.confirmPassword"
              type="password"
              show-password
              placeholder="请再次输入新密码"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPassword">确认修改</el-button>
      </template>
    </el-dialog>
  </header>
</template>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #2C3E50;
  color: white;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.logo-text {
  font-size: 24px;
  font-weight: 600;
  cursor: pointer;
  letter-spacing: 1px;
}

.nav {
  display: flex;
  margin-left: 40px;
  gap: 32px;
}

.nav-item {
  cursor: pointer;
  transition: color 0.3s;
  color: white;
  text-decoration: none;
}

.nav-item:hover {
  color: #FFD700;
}

.nav-item.active {
  color: #FFD700;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
  position: relative;
}

.user-avatar {
  position: relative;
  cursor: pointer;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409EFF;
  transition: transform 0.2s;
}

.avatar-wrapper:hover {
  transform: scale(1.05);
}

.dropdown-menu {
  position: absolute;
  right: 0;
  top: 50px;
  width: 160px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
  padding: 8px 0;
  z-index: 999;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #f5f7fa;
  color: #409EFF;
}

.menu-item el-icon {
  margin-right: 8px;
  font-size: 16px;
}

@media (max-width: 768px) {
  .nav {
    display: none;
  }

  .header {
    padding: 0 16px;
  }

  .user-info {
    gap: 12px;
    flex-direction: column;
  }
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
}

:deep(.el-form-item__label) {
  color: #606266;
}
.user-avatar {
  display: flex;
  align-items: center;
  gap: 8px; /* 控制头像和文字的间距 */
}

.username {
  font-size: 16px; /* 调整文字大小与头像比例协调 */
  line-height: 1; /* 保持行高与头像高度一致 */
}
:deep(.el-form-item__error) {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0;
}
</style>